<template>
  <div class="pro-tree">
    <el-tree
      ref="treeRef"
      show-checkbox
      node-key="id"
      :props="defaultProps"
      @check="handleCheckChange"
      v-bind="$attrs"
      :default-expand-all="true"
    />
  </div>
</template>

<script setup lang="ts">
  import type { ElTree } from 'element-plus'

  const props = defineProps({
    modelValue: {
      type: Array,
      default: () => []
    }
  })
  console.log(props, useAttrs())

  const emit = defineEmits(['update:modelValue'])

  const treeRef = ref<InstanceType<typeof ElTree>>()

  const defaultProps = {
    children: 'children',
    label: 'title'
  }

  // 监听 modelValue 的变化，更新树的选中状态
  watch(
    () => props.modelValue,
    (newVal: string[]) => {
      if (treeRef.value) {
        nextTick(() => {
          // 设置选中的节点
          treeRef.value!.setCheckedKeys(newVal, false)
        })
      }
    },
    { immediate: true }
  )
  onMounted(() => {
    treeRef.value!.setCheckedKeys(props.modelValue, false)
  })

  // 处理节点选中状态变化
  const handleCheckChange = () => {
    if (treeRef.value) {
      const checkedNodes = treeRef.value.getCheckedKeys(false)
      emit('update:modelValue', checkedNodes)
    }
  }

  // 暴露方法给父组件调用
  defineExpose({
    getCheckedKeys: () => treeRef.value?.getCheckedKeys(false),
    setCheckedKeys: (keys: string[]) => treeRef.value?.setCheckedKeys(keys, false)
  })
</script>

<style scoped lang="scss">
  .pro-tree {
    width: 100%;
    padding: 10px;
    max-height: 300px;
    min-height: 100px;
    overflow: auto;
    border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
    border: var(--el-border);
  }
</style>
